package com.android.lovely.user

import androidx.lifecycle.LifecycleOwner
import com.android.lovely.aav.PreferentialManager
import com.android.lovely.api.service.userService
import com.android.lovely.data.UpdateUserLogin
import com.android.lovely.data.UserBean
import com.android.lovely.manager.KVStore
import com.android.lovely.manager.KVStore.registerChangeListener
import com.android.lovely.manager.WorkStore
import com.google.firebase.ktx.Firebase
import com.google.firebase.messaging.ktx.messaging
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.coroutine.applicationScope

/**
 *
 * @author why
 * @date 2025/3/7 18:23
 */
object UserManager {
    val token: String get() = KVStore.token

    var userInfo: UserBean?
        get() = KVStore.loginer
        set(value) {
            KVStore.loginer = value
            value ?: return
            WorkStore.getInstance().buyDialogShowCount = value.adNormalNum
            WorkStore.getInstance().buyPageShowCount = value.adBuyPageNum
        }

    val authId: Int get() = userInfo?.id ?: 0

    inline fun LifecycleOwner.registerAuthChange(crossinline onChange: (UserBean) -> Unit) {
        userInfo?.let { onChange.invoke(it) }
        lifecycle.registerChangeListener { key ->
            if (key == "loginer") {
                val user = userInfo ?: return@registerChangeListener
                onChange.invoke(user)
            }
        }
    }

    fun updateGems(point: Int) {
        userInfo = userInfo?.copy(point = point)
    }

    fun isVip() = userInfo?.isVip() ?: false

    fun isLogin() = token.isNotEmpty() && userInfo != null

    fun isB(): Boolean {
        return KVStore.system?.adult == false && userInfo?.nsfwStatus == 1
    }

    fun isC(): Boolean {
        return KVStore.system?.adult == true
    }

    suspend fun updateAuth(
        authUpdate: (UpdateUserLogin.() -> Unit)? = null
    ) {
        val update = UpdateUserLogin()
        if (authUpdate != null) {
            update.apply(authUpdate)
        }
        userService.updateUserInfo(update)
        refreshAuthSync()
    }

    fun refreshAuth() {
        if (token.isEmpty()) return
        applicationScope.launchSafety {
            refreshAuthSync()
        }
    }

    suspend fun refreshAuthSync() {
        userInfo = userService.refreshUser()
        PreferentialManager.init()
    }

    fun logout() {
        userInfo?.fcmTag?.forEach {
            Firebase.messaging.unsubscribeFromTopic(it)
        }
        KVStore.token = ""
        KVStore.loginer = null
    }
}